<template>
    <div class="font-size-30 height-100 width-100 flex flex-direction-column">
        <zt-table-no-page ref="tableRef" :paramForm="paramForm" :tableData="tableData" :tableColumns="columnsData"
            :tableTitle="tableTitle" @get-data="getCurrData" :api="apiGetMenuTree" row-key="menuId"
            :moreOperations="operationsConfig" :showIndex="false">
            <template #topRight>
                <el-row class="mb-4">
                    <el-button type="primary" :icon="Plus" @click="handerCreateMenu">新增菜单</el-button>
                </el-row>
            </template>
            <template #iconCls="{ row }">
                <div class="flex">
                    <el-icon style="font-size: 18px;">
                        <component :is="row['iconCls']"></component>
                    </el-icon>
                    <div class="margin-l-8">
                        <span>{{ row.iconCls }}</span>
                    </div>
                </div>
            </template>
            <template #moreColumn="{ row, index }">
                <el-button :type="btnType[row.level - 1] || 'success'" size="small" @click="handerAddNextLevelMenu(row)">
                    添加{{ numberToChinese(row.level + 1) }}级菜单
                </el-button>
                <el-button size="small" type="warning" @click.stop="handleAllButton(row)"
                    v-if="!row.children || row.children.length == 0">查看按钮</el-button>
                <el-popover placement="top" :width="200">
                    <template #reference>
                        <el-button type="success" size="small" style="margin-right: 16px">更多操作</el-button>
                    </template>
                    <div style="display: flex;align-items: center;justify-content: center;">
                        <el-button size="small" :icon="Edit" type="primary" @click.stop="handleEdit(row)">修改</el-button>
                        <el-button type="danger" :icon="Delete" size="small" @click.stop="handleDelete(row)">删除</el-button>
                    </div>
                </el-popover>
            </template>
        </zt-table-no-page>
        <add-menu-dialog v-model="showVisible" :currentType="currentType" :objectValue="objectValue"
            @success="handerReload" />

        <button-list-dialog v-model="isVisibleButtonPopup" :objectValue="objectValue" v-if="isVisibleButtonPopup" />
    </div>
</template>

<script  setup>
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus'
import {
    Plus, Delete, Edit
} from '@element-plus/icons-vue'
import { columnsData } from "./configData.js"
import { apiGetMenuTree, apiDeleteMenu } from "@/api/admin/menuManage/api.js"
import { numberToChinese, setNodeLevel } from "@/utils/publicMethod.js"
import addMenuDialog from "./components/add-menu-dialog.vue"
import buttonListDialog from "./components/button-list-dialog.vue"
import { useStore } from '@/store/index'//引入store

const store = useStore();
const router = useRouter();
// 接口参数
const paramForm = reactive({
    catalogId: store.paramsObject.catalogId
})
// 更多列配置信息
const operationsConfig = {
    title: '操作', //标题
    align: 'center',//居中方式
    width: '310px',//宽度
    fixed: 'right',//固定定位方向
}

const tableTitle = ref('')
const tableData = ref([])

const currentType = ref('add') //当前操作类型
const showVisible = ref(false)
const objectValue = ref({})

// 新增菜单按钮
function handerCreateMenu() {
    currentType.value = 'add';
    showVisible.value = true
    objectValue.value = {
        catalogId: store.paramsObject.catalogId
    }
}
// 修改菜单
function handleEdit(row) {
    currentType.value = 'edit';
    showVisible.value = true
    objectValue.value = row
}
// 添加下一级
function handerAddNextLevelMenu(row) {

    currentType.value = 'add';
    showVisible.value = true;
    objectValue.value = {
        menuId: row.menuId,
        level: row.level,
        catalogId: store.paramsObject.catalogId
    }
}
// 删除菜单
const handleDelete = (row) => {
    ElMessageBox.confirm(`你是否确认删除“${row.name}” ? 删除后不可撤回`)
        .then(() => {
            apiDeleteMenu({ menuId: row.menuId }, '菜单删除中').then(res => {
                if (res.success) {
                    ElMessage({
                        message: '菜单删除成功',
                        type: 'success',
                    })
                    handerReload()
                    return false
                }
                ElMessage({
                    message: res.message,
                    type: 'warning',
                })
            })
        })
}
const isVisibleButtonPopup = ref(false)
// 查看所有按钮
function handleAllButton(row) {
    isVisibleButtonPopup.value = true
    objectValue.value = row
}

// 按钮类型
const btnType = ref(['primary', 'success', 'info', 'warning', 'danger', ''])

const tableRef = ref(null)
// 重新加载 表格数据
async function handerReload() {
    tableRef.value.reload() //调用父组件里面的重载方法
}

// 获取当前部门数据
function getCurrData(res) {
    let list = removeEmptyChildren(filterMenus(res.data))
    // 遍历树形数据，设置节点层级
    list.forEach(node => {
        setNodeLevel(node, 1);
    });
    console.log(list)
    tableData.value = list
}
// 删除children字段
function removeEmptyChildren(menuList) {
    const filteredMenus = [];
    for (const menu of menuList) {
        const filteredMenu = { ...menu };
        if (filteredMenu.children && filteredMenu.children.length > 0) {
            filteredMenu.children = removeEmptyChildren(filteredMenu.children);
        } else {
            delete filteredMenu.children;
        }
        filteredMenus.push(filteredMenu);
    }
    return filteredMenus;
}

function filterMenus(menuList) {
    const filteredMenus = [];
    for (const menu of menuList) {
        if (menu.type === 'menu') {
            const filteredMenu = { ...menu };
            if (menu.children && menu.children.length > 0) {
                filteredMenu.children = filterMenus(menu.children);
            } else {
                delete filteredMenu.children;
            }
            filteredMenus.push(filteredMenu);
        }
    }
    return filteredMenus;
}

onMounted(() => {
    tableTitle.value = store.paramsObject?.catalogName + ' - 菜单列表' || '菜单列表'

    // getTableData()
})

</script>

<style lang='scss' scoped></style>